package net.towee.server.bittorrent.impl;

import java.util.Date;
import java.util.Iterator;

import javax.inject.Inject;
import javax.inject.Named;

import net.towee.model.bittorrent.Peer;
import net.towee.model.bittorrent.TorrentData;
import net.towee.server.CoreSettings;
import net.towee.server.bittorrent.AnnounceUpdater;
import net.towee.server.persistence.TorrentStore;

/**
 * Announce updater implementation. It should be run each X minutes to
 * clear torrents peers list 
 * @author c58
 */
public class AnnounceUpdatedImpl implements AnnounceUpdater {
	private final TorrentStore torrStore;
	private final int interval;
	
	private long startTime;

	@Inject
	public AnnounceUpdatedImpl(TorrentStore torrStore,
			@Named(CoreSettings.ANNOUNCE_INTERVAL) int interval) {
		this.torrStore = torrStore;
		this.interval = interval;
	}
	
	@Override
	public void run() {
		// Set start date
		startTime = new Date().getTime();
		
		// Get torrents
		Iterator<TorrentData> it = torrStore.getTorrents().iterator();
		
		// Update each torrent
		while(it.hasNext()) {
			updatePeer(it.next());
		}
	}

	@Override
	public void updatePeer(TorrentData torrent) {
		Iterator<Peer> peers = torrent.getPeersList().iterator();
		
		// Clear list
		while(peers.hasNext()) {
			if( (startTime - peers.next().getLastRequestDate().getTime()) > interval )
				peers.remove();
		}
		
		// Save torrent
		torrStore.updateTorrent(torrent);
	}

}